/**
 * Created by Dalyn on 2017/3/20.
 * 金融中心-贷款记录
 */
import React from "react";
import {hashHistory} from 'react-router';
import Relay from "react-relay";
import GetLoanRecordListMutation from "./mutation/GetLoanRecordListMutation"
import Confirm from "../../common/Confirm"
import InputBox from "../../common/InputBox"
import "./css/loan.css";

/*导出组件*/
export default class LoanFinance extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            listInfo: [],
            /*总共多少条*/
            totalResult: "",
            /*贷款总额*/
            sumMoney:"",
            /*贷款总利息*/
            sumInterest:"",
            /*每页条数*/
            pageItem: "",
            /*指定页码*/
            pageNum: 1,
            /*指定每页显示条数*/
            pageSize: 10,
            /*0-未还款，1-已还款*/
            status: "",
            /*借款公司名*/
            partyBEnName:"",
            /*后台错误提示*/
            hint: "",
        };
        this.style = {
            confirm: {
                width: '90px',
                height: '28px',
                backgroundColor: "#f7f5f5",
                fontSize: "14px",
                color: "#333333",
                fontFamily: "Microsoft YaHei",
                border:"1px solid #ededed",
                borderRadius: "5px",
                marginLeft: "30px",
                padding:"5px 25px"
            },
            confirm_active: {
                width: '90px',
                height: '30px',
                backgroundColor: "#7abd54",
                fontSize: "14px",
                color: "#fff",
                fontFamily: "Microsoft YaHei",
                borderRadius: "5px",
                marginLeft: "30px",
                padding:"5px 25px"
            },
            company: {
                width: "150px",
                height: "20px",
                borderColor: "#c2df88",
                // marginTop: "15px"
            },
            page_ensure:{
                width: '50px',
                height: '25px',
                backgroundColor: "#7abd54",
                fontSize: "12px",
                color: "#fff",
                fontFamily: "Microsoft YaHei",
                borderRadius: "3px",
                marginLeft: "10px",
                marginTop: "-4px"
            }
        };
        // this.listInfo=[
        //     {date:"2017-03-13",money:"123.123.123.00",days:"66",rate:"8.88%",interest:"10",purpose:"订单",order:"WWYK－20170228-0010",state:"待还款"},
        //     {date:"2017-03-13",money:"123.123.123.00",days:"66",rate:"8.88%",interest:"10",purpose:"订单",order:"WWYK－20170228-0010",state:"待还款"},
        //     {date:"2017-03-13",money:"123.123.123.00",days:"66",rate:"8.88%",interest:"10",purpose:"订单",order:"WWYK－20170228-0010",state:"待还款"},
        //     {date:"2017-03-13",money:"123.123.123.00",days:"66",rate:"8.88%",interest:"10",purpose:"订单",order:"WWYK－20170228-0010",state:"待还款"},
        // ]
        this.pageNum=1;
    }

    ///adadss

    myRelay() {
        if(this.refs.search){//如果存在，说明已经初始化完成，需要校验后再查询数据
            let text = this.refs.search.state.text;
            let reg = /^[a-zA-Z\u4e00-\u9fa5（）]+$/;
            if(text && !reg.test(text)){
                this.setState({
                    listInfo: [],
                    totalResult: "0",
                    pageItem: "0",
                    sumMoney:"0.00",
                    sumInterest:"0.00",
                    pageNum: "1",
                });
                this.refs.page.value = this.state.pageNum;
                return;
            }
        }
        Relay.Store.commitUpdate(
            new GetLoanRecordListMutation({
                pageNum: this.state.pageNum,
                pageSize: this.state.pageSize,
                status: this.state.status,
                partyBEnName:this.state.partyBEnName,
            }),
            {
                onFailure: () => {
                    console.log("请求失败")
                },
                onSuccess: (response) => {
                    let data = response.getLoanRecordList.data;
                    // console.log(data)
                    if (data.errorCode === "0") {
                        this.setState({
                            listInfo: data.loanRecordList,
                            totalResult: data.totalResult,
                            pageItem: data.loanRecordList.length,
                            sumMoney:data.sumMoney,
                            sumInterest:data.sumInterest,
                        });
                        this.refs.page.value = this.state.pageNum;
                    } else {
                        this.setState({
                            hint: data.value,
                        });
                    }
                }

            }
        );
    }
    /*日期格式化*/
    dateFormat(time){
        let zero=(n)=>{
            return n = n>=0&&n<10 ? "0"+n : n;
        };
        let y = new Date(time).getFullYear();
        let m = new Date(time).getMonth()+1;
        let d = new Date(time).getDate();
        // let h = new Date(time).getHours();
        // let ms = new Date(time).getMinutes();

        // return zero(y)+"-"+zero(m)+"-"+zero(d)+" "+zero(h)+":"+zero(ms);
        return zero(y)+"-"+zero(m)+"-"+zero(d)
    }

    /*数字千分制*/
    doubleFormat(obj){
        if(!obj){
            return obj;
        }else{
            return parseFloat(obj).toLocaleString();
        }
    }

    componentWillMount() {
        this.myRelay();
    }

    /*绑定数据*/
    addList() {
        if( null == this.state.listInfo || this.state.listInfo.length == 0){
            return (
                <tr>
                    <td>暂无相关数据</td>
                </tr>
            )
        }else{
            return this.state.listInfo.map((item, index) => {
                return (
                    <tr key={index + "_"}>
                        <td>{this.dateFormat(item.startTime)}</td>
                        <td title={item.useNo}>{item.useNo}</td>
                        <td title={!item.partyBEnName?"--":item.partyBEnName} >{!item.partyBEnName?"--":item.partyBEnName}</td>
                        <td>{this.doubleFormat(item.money)}</td>
                        <td>{item.region}</td>
                        <td>{item.dayRate}</td>
                        <td>{this.doubleFormat(item.interest)}</td>
                        <td>{item.status == 0 ? "未还款" : "已还款"}</td>
                    </tr>
                )
            })
        }

    }

    /*全部*/
    whole() {
        this.setState({
            status:"",
            pageNum: "1",
        },this.search);
    }

    /*待还款*/
    pending() {
        this.setState({
            status: "0",
            pageNum: "1",
        }, this.search);
    }

    /*已还款*/
    already() {
        this.setState({
            status: "1",
            pageNum: "1",
        }, this.search);
    }

    /*模糊搜索*/
    search() {
        this.setState({
            partyBEnName: this.refs.search.state.text,
            pageNum: "1",
            pageSize: this.state.pageSize,
        }, this.myRelay);
    }

    /*页面表单失去焦点时*/
    bluron(type) {
        switch (type) {
            case "search":
                this.setState({
                    partyBEnName: this.refs.search.state.text,
                });
                return;
            case "page":{
                let pageNum = this.refs.page.value;

                if (pageNum<1){
                    this.setState({
                        pageNum:1
                    });
                }
                if (pageNum > this.pageTotal()){
                    this.setState({
                        pageNum:this.pageTotal()
                    });
                }
                if(this.refs.page.value == ""){
                    this.setState({
                        pageNum:this.pageNum
                    });
                }
                return;

             /*   this.setState({
                    pageNum: this.refs.page.value == "" ? this.state.pageNum : this.refs.page.value,
                });
                return;*/
            }
        }
    }
    /*获取焦点*/
    focuson(type){
        switch (type){
            case "search":
                this.setState({
                    hint:""
                });
                return;
        }
    }

    /**
     * 当输入页码时进行校验
     */
    pageNumChange(e){
        let numtest = /^[0-9]*$/;
        let text = e.target.value;
        if (!numtest.test(text)) {
            return;
        }
        this.setState({
            pageNum:text
        });
    }

    /*页码*/
    page() {
        this.bluron();
        this.setState({
            pageNum:this.refs.page.value == ""?"1":this.refs.page.value,
        },this.myRelay);
        this.refs.page.value = this.state.pageNum;
    }
    /*总页数*/
    pageTotal() {
        return Math.ceil(this.state.totalResult / this.state.pageSize)
    }

    /*上一页*/
    leftBtn() {
        let pageNum = this.state.pageNum;
        if (pageNum <= 1) {
            return;
        } else {
            pageNum--;
            this.pageNum = pageNum;
            // this.bluron();
            this.setState({
                pageNum: pageNum,
            }, this.myRelay)
        }
    }

    /*下一页*/
    rightBtn() {
        let pageTotal = this.pageTotal();
        let pageNum = this.state.pageNum;
        if (pageNum >= pageTotal) {
            return;
        } else {
            pageNum++;
            this.pageNum = pageNum;
            this.setState({
                pageNum: pageNum,
            }, this.myRelay)
        }
    }
    render() {
        return (
            <div className="loan_rec">
                {/*<p className="loan_rec_nav1">金融中心 > <span className="loan_rec_nav2">贷款记录</span></p>*/}
                <div className="loan_rec_box">
                    <div className="loan_rec-clear">
                        <div className="_left">
                            <span className="loan_rec_tab">状态：</span>
                            <span style={this.state.status == ""?this.style.confirm_active:this.style.confirm}  data-type="btn" onClick={this.whole.bind(this)}>全部</span>
                            <span style={this.state.status == "0"?this.style.confirm_active:this.style.confirm} data-type="btn" onClick={this.pending.bind(this)}>待还款</span>
                            <span style={this.state.status == "1"?this.style.confirm_active:this.style.confirm} data-type="btn" onClick={this.already.bind(this)}>已还款</span>
                        </div>

                        <div className="loan_rec_search clear _right loan_rec-clear">
                            <div className="loan_rec_searchInp _left">
                                <InputBox titletext={'借款方：'} className="loan_border-none" space={20} style={this.style.company} defaultvalute="请输入公司名称"
                                          maxlength={22} ref={'search'} bluron={this.bluron.bind(this, "search")} focuson={this.focuson.bind(this,"search")}/>
                            </div>
                            <div className="loan_rec_searchBtn _left">
                                <Confirm style={this.style.confirm_active} tcontext={'搜索'} touch={this.search.bind(this)}/>
                                <span className="loan_rec_searchHint">{this.state.hint}</span>
                            </div>
                        </div>
                    </div>

                    <ul className="loan_rec_ul">
                        <li className="loan_rec_t">
                            <span className="loan_rec_tsp">借款记录</span>
                            <span className="loan_rec_tsp" data-type="head">贷款总金额：</span>
                            <span className="loan_rec_tsp loan_rec-bold">{this.doubleFormat(this.state.sumMoney)}</span>
                            <span className="loan_rec_tsp" data-type="head">利息：</span>
                            <span className="loan_rec_tsp loan_rec-bold">{this.doubleFormat(this.state.sumInterest)}</span>
                        </li>
                    </ul>

                    <table className="settle_rec_table" style={{marginTop:0}}>
                        <thead>
                            <tr>
                                {
                                    ["申请时间","订单","借款方","贷款金额（元）","借款天数","日利率（%）","利息（元）","状态"].map((item,index)=>
                                        <th> {item} </th>
                                    )
                                }
                            </tr>
                        </thead>
                        <tbody>
                            {
                                    this.addList()
                            }
                        </tbody>
                    </table>
                    <div className="loan_page clear">
                        <ol className="loan_page_ol clear">
                            <li className="loan_page_oli1">总计<span>{this.state.totalResult}</span>条</li>
                            <li className="loan_page_oli2">每页<span>{this.state.pageItem}</span>条</li>
                            <li className="loan_page_oli3">
                                共<span>{this.pageTotal()}</span>页
                            </li>
                            <li>第&nbsp;&nbsp;<input type="text" className="loan_page_olinp" ref={"page"} value={this.state.pageNum}
                                                    onBlur={this.bluron.bind(this, "page") } onChange={this.pageNumChange.bind(this)}/>&nbsp;&nbsp;页
                            </li>
                            <li><Confirm tcontext={'确定'} style={this.style.page_ensure} touch={this.page.bind(this)}
                                         bluron/>
                            </li>
                            <li className="loan_page_olbtn">
                                <i className="loan_page_button loan_page_left" onClick={this.leftBtn.bind(this)}></i>
                                <i className="loan_page_button loan_page_right" onClick={this.rightBtn.bind(this)}></i>
                            </li>
                        </ol>
                    </div>
                </div>
            </div>
        )
    }
}